package com.ltedu.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ltedu.common.contants.Constants;
import com.ltedu.course.domain.Chapter;
import com.ltedu.course.domain.Video;
import com.ltedu.course.domain.dto.ChapterDTO;
import com.ltedu.course.domain.dto.VideoDTO;
import com.ltedu.course.mapper.ChapterMapper;
import com.ltedu.course.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltedu.course.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程章节表 服务实现类
 * </p>
 *
 * @author Jerry
 * @since 2020-12-10
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterDTO> getChapterList(Long courseId) {
        LambdaQueryWrapper<Chapter> chapterWrapper = new LambdaQueryWrapper<>();
        chapterWrapper.eq(Chapter::getState, Constants.NORMAL);
        chapterWrapper.eq(Chapter::getCourseId, courseId);
        // 章节列表
        List<Chapter> chapterList = this.baseMapper.selectList(chapterWrapper);

        LambdaQueryWrapper<Video> videoWrapper = new LambdaQueryWrapper<>();
        videoWrapper.eq(Video::getState, Constants.NORMAL);
        videoWrapper.eq(Video::getCourseId, courseId);
        // 小节列表
        List<Video> videoList = videoService.list(videoWrapper);
        // 组装数据
        List<ChapterDTO> chapterDTOList = chapterList.stream().map(chapter -> {
            ChapterDTO chapterDTO = new ChapterDTO();
            BeanUtils.copyProperties(chapter, chapterDTO);
            List<VideoDTO> videoDTOList = new ArrayList<>();
            videoList.forEach(video -> {
                // 小节里面chapterid和章节里面id是否一样
                if (chapter.getId().equals(video.getChapterId())){
                    VideoDTO videoDTO = new VideoDTO();
                    BeanUtils.copyProperties(video, videoDTO);
                    videoDTOList.add(videoDTO);
                }
            });
            chapterDTO.setChildren(videoDTOList);
            return chapterDTO;
        }).collect(Collectors.toList());
        return chapterDTOList;
    }
}
